import {getSessInfo, logout} from "@/api/user";

function getPermFuncCodes(syslist) {
  let perm_func_codes = []
  syslist.forEach(sys => {
    if (sys.func && sys.func.length > 0) {
      sys.func.forEach(func => {
        if (!perm_func_codes.includes(func.code)) {
          perm_func_codes.push(func.code)
        }
      })
    }
  })
  return perm_func_codes
}

const state = {
  token: '',
  islogin: false,
  isselectcorp: false,
  userinfo: {},
  corpinfo: {},
  subinfo: {},
  syslist: [],
  newsyslist: [],
  perm_func_codes: []
}

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_ISLOGIN: (state, islogin) => {
    state.islogin = islogin
  },
  SET_ISSELECTCORP: (state, isselectcorp) => {
    state.isselectcorp = isselectcorp
  },
  SET_USERINFO: (state, user) => {
    state.userinfo = user
  },
  SET_CORPINFO: (state, corp) => {
    state.corpinfo = corp
  },
  SET_SUBINFO: (state, sub) => {
    state.subinfo = sub
  },
  SET_SYSLIST: (state, sys) => {
    state.syslist = sys
  },
  SET_NEWSYSLIST: (state, syslist) => {
    state.newsyslist = syslist
  },
  SET_PERM_FUNC_CODES: (state, codes) => {
    state.perm_func_codes = codes
  }
}

const actions = {
  getSessInfo({commit}) {
    return new Promise((resolve, reject) => {
      getSessInfo().then(response => {
        const { data } = response
        const {islogin, accesstoken, isselectcorp} = data
        commit('SET_TOKEN', accesstoken)
        commit('SET_ISLOGIN', islogin)
        commit('SET_ISSELECTCORP', isselectcorp)
        const {user, corp, sub} = data.info
        commit('SET_USERINFO', user)
        commit('SET_CORPINFO', corp)
        commit('SET_SUBINFO', sub)
        commit('SET_SYSLIST', data.sys)
        const perm_func_codes = getPermFuncCodes(data.sys)
        commit('SET_PERM_FUNC_CODES', perm_func_codes)
        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },
  logout({commit}) {
    return new Promise((resolve, reject) => {
      logout().then(response => {
        if (response.errcode == 0) {
          commit('SET_USERINFO', {})
          commit('SET_CORPINFO', {})
          commit('SET_SUBINFO', {})
          commit('SET_SYSLIST', [])
        }
        resolve(response)
      }).catch(error => {
        console.log(error);
        reject(error)
      })
    })
  },
  contactSyslist({commit}, projectRoutes) {
    return new Promise((resolve) => {
      state.syslist.forEach(sys => {
        if (sys.code == 'VCLOUD_PROJECT') {
          sys.route.forEach(route => {
            projectRoutes.forEach(r => {
              if (route.path == r.path) {
                route.children = r.children
              }
            })
          })
        }
      })
      commit('SET_NEWSYSLIST', state.syslist)
      resolve(state.syslist)
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
